package com.kingsailor.gunsmith;

import edu.jetwinner.spring.SpringBootAppContextHandler;
import edu.jetwinner.spring.YmlPropertySourceFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@PropertySource(value = {"classpath:fastapp-config.yml"}, factory = YmlPropertySourceFactory.class)
@ConfigurationProperties(prefix = "fastapp.config")
public class FastAppConfigHolder {

    private static final FastAppConfigHolder fakedObj = new FastAppConfigHolder();

    public static final FastAppConfigHolder me() {
        try {
            return SpringBootAppContextHandler.me().getBean(FastAppConfigHolder.class);
        } catch (Exception e) {
            return fakedObj;
        }
    }

    Map<String, String> rawData = new HashMap<>();

    public Map<String, String> getRawData() {
        return rawData;
    }

    public void setRawData(Map<String, String> rawData) {
        this.rawData = rawData;
    }

    public String getProperty(String key) {
        return getProperty(key, null);
    }

    public String getProperty(String key, String defaultValue) {
        String val = rawData.get(key);
        if (val == null) {
            val = defaultValue == null ? key : defaultValue;
        }
        return val;
    }
}
